import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_data_base.dart';
import 'package:safemap/safemap.dart';

// 服务器骑行记录keys
class ServerRidingRecordKeys {
  static const KEY_ID = 'id';
  static const KEY_RECORD_TIME = 'record_time';
  static const KEY_MAX_SPEED = 'max_speed';
  static const KEY_MAX_POWER = 'max_power';
  static const KEY_MAX_MOTOR_POWER = 'max_motor_power';
  static const KEY_MAX_MOS_TEMP = 'max_mos_temp';
  static const KEY_MAX_MOTOR_TEMP = 'max_motor_temp';
  static const KEY_MILEAGE = 'mileage';
  static const KEY_CONSUMPTION = 'consumption';
  static const KEY_RECOVERY = 'recovery';
  static const KEY_RIDE_TIME = 'ride_time';
  static const KEY_POWER_ON_TIME = 'power_on_time';
}

// 车辆单次统计数据
class VehicleStatisticsOnce extends VehicleDataBase {
  // index 从1开始
  int index = 0;

  int count = 0; // 统计数据总数

  int mileage = 0; // 本次里程
  int singleConsumption = 0; // 本次消耗能量
  int singleRecovery = 0; // 本次能量回收
  int singleRideTime = 0; // 本次持续时间

  // 获取骑行时长
  Duration get ridingDuration {
    return Duration(seconds: singleRideTime);
  }

  int singlePowerOnTime = 0; // 本次通电时间

  // 获取开机时长
  Duration get powerOnDuration {
    return Duration(seconds: singlePowerOnTime);
  }

  // year, month, day, hour, minute, second
  int year = 0;
  int month = 0;
  int day = 0;
  int hour = 0;
  int minute = 0;
  int second = 0;

  // 获取完整的骑行日期时间
  DateTime get date {
    return DateTime(year, month, day, hour, minute, second);
  }

  double maxSpd = 0.0; // 本次最高速度
  double maxPower = 0.0; // 本次最高功率
  int maxMotorPower = 0; // 本次最高电机功率
  int maxMosTemp = 0; // 本次最高MOS温度
  int maxMotorTemp = 0; // 本次最高电机温度
  int maxBatteryTemp = 0; // 本次最高电池温度
  int maxBoardTemp = 0; // 本次最高主板温度

  String get singleRideTimeString {
    int hours = singleRideTime ~/ 3600;
    int minutes = (singleRideTime % 3600) ~/ 60;
    int seconds = singleRideTime % 60;
    // 当有小时，则只显示小时
    if (hours > 0) {
      return "$hours h";
    } else if (minutes > 0) {
      return "$minutes min";
    } else {
      return "$seconds s";
    }
  }

  // 总消耗能量，单位转换为kW，功率(kW) = 能量(kJ) ÷ 时间(秒)
  double get singleEnergyConsumption {
    // 将 kJ 转换为 kW
    if (singleRideTime < 60) return 0;
    return (singleConsumption / singleRideTime).toDouble();
  }

  // 回收能量，单位转换为kW，功率(kW) = 能量(kJ) ÷ 时间(秒)
  double get singleEnergyRecovery {
    // 将 kJ 转换为 kW
    if (singleRideTime < 60) return 0;
    return (singleRecovery / singleRideTime).toDouble();
  }

  // 本次里程，单位转换为km
  double get singleMileage {
    return mileage / 100.0;
  }

  // 本次平均速度
  double get avgSpeed {
    // 60s 以上才计算平均速度
    if (singleRideTime < 60) return 0;
    return mileage / singleRideTime * 3600 / 100.0;
  }

  // 本次平均功率
  double get avgPower {
    if (singleRideTime < 60) return 0.0; // 避免除零错误
    // 计算净能量消耗 (单位: kJ)
    double netEnergy = (singleConsumption - singleRecovery) * 0.01;
    // 功率 = 能量 / 时间 (单位: kW)
    double averagePower = netEnergy / singleRideTime;
    return averagePower;
  }

  VehicleStatisticsOnce.fromMap(Map<String, dynamic>? data)
      : super.fromMap(data) {
    SafeMap safeMap = SafeMap(data);

    index = safeMap['index'].toInt ?? safeMap['record_id'].toInt ?? 0;
    count = safeMap['count'].toInt ?? 0;
    mileage = (safeMap['single_mileage'].toDouble ??
            safeMap['record_info']['mileage'].toDouble ??
            0)
        .toInt();
    singleConsumption = safeMap['single_consumption'].toInt ??
        safeMap['record_info']['consumption'].toInt ??
        0;
    singleRecovery = safeMap['single_recovery'].toInt ??
        safeMap['record_info']['recovery'].toInt ??
        0;
    singleRideTime = safeMap['single_ride_time'].toInt ??
        safeMap['record_info']['ride_time'].toInt ??
        0;
    singlePowerOnTime = safeMap['single_power_on_time'].toInt ??
        safeMap['record_info']['power_on_time'].toInt ??
        0;

    // 日期兼容 record_time 字段（毫秒时间戳）
    if (safeMap['date'].map != null) {
      year = safeMap['date']['year'].toInt ?? 0;
      month = safeMap['date']['month'].toInt ?? 0;
      day = safeMap['date']['day'].toInt ?? 0;
      hour = safeMap['date']['hour'].toInt ?? 0;
      minute = safeMap['date']['minute'].toInt ?? 0;
      second = safeMap['date']['second'].toInt ?? 0;
    } else if (safeMap['record_time'].string != null &&
        safeMap['record_time'].string!.isNotEmpty) {
      DateTime dt = DateTime.parse(safeMap['record_time'].string!).toLocal();
      year = dt.year;
      month = dt.month;
      day = dt.day;
      hour = dt.hour;
      minute = dt.minute;
      second = dt.second;
    }

    maxSpd = (safeMap['maxSpeed'].toInt ??
            safeMap['max_speed'].toInt ??
            safeMap['record_info']['max_speed'].toInt ??
            0) /
        100;
    maxPower = (safeMap['maxPower'].toInt ??
            safeMap['max_power'].toInt ??
            safeMap['record_info']['max_power'].toInt ??
            0) /
        1000;
    maxMotorPower = safeMap['maxMotorPower'].toInt ??
        safeMap['max_motor_power'].toInt ??
        safeMap['record_info']['max_motor_power'].toInt ??
        0;
    maxMosTemp = safeMap['maxMosTemp'].toInt ??
        safeMap['max_mos_temp'].toInt ??
        safeMap['record_info']['max_mos_temp'].toInt ??
        0;
    maxMotorTemp = safeMap['maxMotorTemp'].toInt ??
        safeMap['max_motor_temp'].toInt ??
        safeMap['record_info']['max_motor_temp'].toInt ??
        0;
    maxBatteryTemp = safeMap['maxBatteryTemp'].toInt ??
        safeMap['max_battery_temp'].toInt ??
        0;
    maxBoardTemp =
        safeMap['maxBoardTemp'].toInt ?? safeMap['max_board_temp'].toInt ?? 0;
  }

  // 当前数据是否有效
  bool get isValid {
    return year != 0 && index != 0 && mileage < 1000;
  }

  Map<String, dynamic> toMap() {
    return {
      'index': index,
      'count': count,
      'date': {
        'year': year,
        'month': month,
        'day': day,
        'hour': hour,
        'minute': minute,
        'second': second,
      },
      'mileage': mileage,
      'single_mileage': mileage,
      'single_consumption': singleConsumption,
      'single_recovery': singleRecovery,
      'single_ride_time': singleRideTime,
      'single_power_on_time': singlePowerOnTime,
      'maxSpeed': (maxSpd * 100).toInt(),
      'maxPower': (maxPower * 1000).toInt(),
      'maxMotorPower': maxMotorPower,
      'maxMosTemp': maxMosTemp,
      'maxMotorTemp': maxMotorTemp,
      'maxBatteryTemp': maxBatteryTemp,
      'maxBoardTemp': maxBoardTemp,
    };
  }

  Map<String, dynamic> toMapToUploadServer() {
    return {
      ServerRidingRecordKeys.KEY_ID: index,
      ServerRidingRecordKeys.KEY_RECORD_TIME: date.millisecondsSinceEpoch,
      ServerRidingRecordKeys.KEY_MAX_SPEED: maxSpd,
      ServerRidingRecordKeys.KEY_MAX_POWER: maxPower,
      ServerRidingRecordKeys.KEY_MAX_MOTOR_POWER: maxMotorPower,
      ServerRidingRecordKeys.KEY_MAX_MOS_TEMP: maxMosTemp,
      ServerRidingRecordKeys.KEY_MAX_MOTOR_TEMP: maxMotorTemp,
      ServerRidingRecordKeys.KEY_MILEAGE: singleMileage,
      ServerRidingRecordKeys.KEY_CONSUMPTION: singleEnergyConsumption,
      ServerRidingRecordKeys.KEY_RECOVERY: singleEnergyRecovery,
      ServerRidingRecordKeys.KEY_RIDE_TIME: singleRideTime,
      ServerRidingRecordKeys.KEY_POWER_ON_TIME: singlePowerOnTime,
    };
  }
}

// 单次统计数据 {index: 131, date: {year: 5, month: 9, day: 29, hour: 11, minute: 29, second: 14}, maxSpeed: 0, 
// maxPower: 0, maxMotorPower: 0, maxMosTemp: -46, maxMotorTemp: -46, maxBatteryTemp: -46, 
// maxBoardTemp: -46, mileage: 0, consumption: 0, recovery: 0, rideTime: 0, powerOnTime: 615}
